import { createSlice, createAsyncThunk, type PayloadAction } from "@reduxjs/toolkit";
import * as API from "../api/http";
import type { hrlistTS } from "./crmsTS";

type initialStateTS = {
    hrlist: Array<hrlistTS>
}

//存储数据
let initialState: initialStateTS = {
    hrlist: [],//岗位管理数据
}

const todosSlice = createSlice({
    name: "todos",
    initialState,
    reducers: { //同步操作

        //获取岗位管理数据
        t_getlist(state: initialStateTS, action: PayloadAction<Array<hrlistTS>>) {
            state.hrlist = action.payload
        },
        //添加数据
        t_addlist(state: initialStateTS, action: PayloadAction<hrlistTS>) {
            state.hrlist.push(action.payload)
        },
        //编辑数据
        t_updatelist(state: initialStateTS, action: PayloadAction<hrlistTS>) {
            let i = state.hrlist.findIndex(item => {
                return item.id == action.payload.id
            })
            state.hrlist[i] = action.payload
        },
        //编辑数据
        t_dellist(state: initialStateTS, action: PayloadAction<number>) {
            state.hrlist = state.hrlist.filter(item => {
                return item.id !== action.payload
            })
        }

    },
});

export const actionfn = todosSlice.actions;
export default todosSlice.reducer;

//异步操作 获取岗位管理数据
export let async_getlist = createAsyncThunk('async_getlist', async (_, store) => {
    //调取接口
    let res = await API.http_getlist()
    //同步修改异步
    store.dispatch(actionfn.t_getlist(res))
})

//异步操作 搜索岗位数据
export let async_searchlist = createAsyncThunk('async_searchlist', async (obj: any, store) => {
    //调取接口
    let res = await API.http_searchlist(obj)
    //同步修改异步
    store.dispatch(actionfn.t_getlist(res))
})

//异步操作 添加数据
export let async_addlist = createAsyncThunk('async_addlist', async (obj: hrlistTS, store) => {
    //调取接口
    let res = await API.http_addlist(obj)
    //同步修改异步
    store.dispatch(actionfn.t_addlist(res))
})

//异步操作 编辑数据
export let async_updatelist = createAsyncThunk('async_updatelist', async (obj: hrlistTS, store) => {
    //调取接口
    let res = await API.http_updatelist(obj)
    //同步修改异步
    store.dispatch(actionfn.t_updatelist(res))
})

//异步操作 删除数据
export let async_dellist = createAsyncThunk('async_dellist', async (id: number, store) => {
    //调取接口
    await API.http_dellist(id)
    //同步修改异步
    store.dispatch(actionfn.t_dellist(id))
})